package com.z.xhelper.core.socket;

import com.z.xhelper.core.config.BeanContainer;
import com.z.xhelper.core.config.Consts;
import com.z.xhelper.core.eventbus.EventBus;
import com.z.xhelper.core.events.MsgSendEvent;
import com.z.xhelper.core.utils.LogUtil;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Date;
import java.util.Objects;

public class WebSocket {
    private static WebSocketClient ws;

    public WebSocket() {
        new Thread(() -> {
            while (true) {
                try {
                    Thread.sleep(3000);
                    if (ws == null || ws.isClosed() || ws.isClosing()) {
                        ws();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public void ws() {
        URI serverURI = URI.create(Consts.SOCKET_SERVER_URL);
        ws = new WebSocketClient(serverURI) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                LogUtil.log("socket 开启" + handshakedata.getHttpStatusMessage());
            }

            @Override
            public void onMessage(String message) {
                LogUtil.log("socket 收到消息" + message);
                if (message.contains(Consts.PING)) {
                    return;
                }
                Objects.requireNonNull(BeanContainer.getBean(EventBus.class))
                        .post(new MsgSendEvent(message));
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {

                String sb = "onClose at time：" +
                        new Date() +
                        "\n" +
                        "onClose info:" +
                        code +
                        reason +
                        remote +
                        "\n";
                LogUtil.log(sb);
            }

            @Override
            public void onError(Exception ex) {

                String sb = "onError at time：" +
                        new Date() +
                        "\n" +
                        ex +
                        "\n";
                LogUtil.log(sb);
            }
        };
        ws.connect();
    }

    /**
     * 发送消息到 socket 服务端
     *
     * @param msg 消息
     */
    public void send(String msg) {
        if (ws.isClosed() || ws.isClosing()) {
            ws.connect();
        }
        // 发送消息
        LogUtil.log("socket 发送消息" + msg);
        LogUtil.log(ws.toString());
        ws.send(msg);
    }

    public boolean isOnline() {
        return ws != null && ws.isOpen();
    }
}
